package com.example.studyktdemo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.studyktdemo.bean.CateGoryResponse
import com.example.studyktdemo.bean.CateGoryResponseItem
import com.example.studyktdemo.databinding.ItemCategoryBinding

class CategoryAdapter : RecyclerView.Adapter<CategoryAdapter.InnerHolder>() {

    private var mCategoryItemClick: CategoryItemClick? = null
    private var mCategoryList = CateGoryResponse()

    class InnerHolder(var binding: ItemCategoryBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(cateGoryResponseItem: CateGoryResponseItem) {
            Glide.with(binding.root).load(cateGoryResponseItem.bgPicture).into(binding.ivCategory)
            binding.tvCategoryName.text = "#" + cateGoryResponseItem.name
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerHolder {
        val binding =
            ItemCategoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)

        return InnerHolder(binding)
    }

    override fun onBindViewHolder(holder: InnerHolder, position: Int) {
        holder.bind(mCategoryList[position])
        holder.itemView.setOnClickListener {
            mCategoryItemClick?.itemClick()
        }
    }

    override fun getItemCount(): Int {
        return if (mCategoryList.size == 0) {
            0
        } else {
            mCategoryList.size
        }
    }

    fun setData(categoryList: CateGoryResponse) {
        mCategoryList = categoryList
        notifyDataSetChanged()
    }

    interface CategoryItemClick {
        fun itemClick()
    }

    fun setCategoryItemClick(click: CategoryItemClick) {
        mCategoryItemClick = click
    }
}